import { ITile } from '../Map'
import DataManager from '../Runtime/DataManager'
const { blockWidth, blockHeight } = DataManager.Instance
import { IMapInfo, TileType } from '../Type/game'
const hasVisited = (visitedMap, i, j) => {
    const key = `${i},${j}`
    return visitedMap[key]
}
export function getAccessableMap(
    mapInfo: Array<Array<ITile>>,
    startPoint = { x: 0, y: 0 },
    endPoint = { x: 1, y: 0 },
): Array<IMapInfo> {
    const queue: Array<IMapInfo> = []
    const row = mapInfo.length,
        column = mapInfo[0].length
    const visited = {}
    let i = startPoint['x'],
        j = startPoint['y']
    do {
        let block = mapInfo[i][j]
        const key = `${i},${j}`

        visited[key] = 1
        if (block.src && block.type == TileType.house) {
            queue.push({
                left: j * blockWidth,
                top: -1 * i * blockHeight,
                houseId: block.houseId,
                type: block.type,
                chanceId: block.chanceId,
                destinyId: block.destinyId,
            })
        }
        // 假定地图是连续的, 且能形成环
        // 从右,下,左,上四个角度进行检索
        if (j + 1 < column && !hasVisited(visited, i, j + 1) && mapInfo[i][j + 1].src) {
            j++
        } else if (i + 1 < row && !hasVisited(visited, i + 1, j) && mapInfo[i + 1][j].src) {
            i++
        } else if (j - 1 >= 0 && !hasVisited(visited, i, j - 1) && mapInfo[i][j - 1].src) {
            j--
        } else if (i - 1 >= 0 && !hasVisited(visited, i - 1, j) && mapInfo[i - 1][j].src) {
            i--
        } else {
            throw new Error('map is not circle')
        }
    } while (!(i == endPoint.x && j == endPoint.y))
    const finalBlock = mapInfo[i][j]
    queue.push({
        left: j * blockWidth,
        top: -1 * i * blockHeight,
        houseId: finalBlock.houseId,
        type: finalBlock.type,
        chanceId: finalBlock.chanceId,
        destinyId: finalBlock.destinyId,
    })
    return queue
}
